<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>知识库管理 - AI智能体开发平台</title>
    <link rel="stylesheet" href="layui/css/layui.css">
    <link rel="stylesheet" href="za.css">
</head>
<body style="background-color: #FFFFFF; margin: 0; padding: 20px;">
    <div class="page-header" style="margin-bottom: 20px;">
        <h2>知识库管理</h2>
        <p style="color: #909399; margin-top: 8px;">管理智能体关联的知识库内容，支持增删改查操作</p>
    </div>
    
    <!-- 关联智能体信息 -->
    <div class="layui-card" style="margin-bottom: 20px;">
        <div class="layui-card-body">
            <div class="layui-row">
                <div class="layui-col-md6">
                    <div class="layui-form-item" style="margin-bottom: 0;">
                        <label class="layui-form-label" style="width: 100px;">关联智能体：</label>
                        <div class="layui-input-block">
                            <span class="layui-form-text" style="font-weight: 500; color: #303133;" id="agentInfo">客服助手（ID: 1）</span>
                        </div>
                    </div>
                </div>
                <div class="layui-col-md6" style="text-align: right;">
                    <button class="za-btn za-btn-primary" id="btnAddKnowledge" style="margin-left: 10px;">
                        <i class="layui-icon layui-icon-add-circle" style="margin-right: 5px;"></i>添加知识
                    </button>
                    <button class="za-btn za-btn-secondary" id="btnBatchDelete" style="margin-left: 10px; display: none;">
                        <i class="layui-icon layui-icon-delete" style="margin-right: 5px;"></i>批量删除
                    </button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 搜索和筛选区域 -->
    <div class="layui-card" style="margin-bottom: 20px;">
        <div class="layui-card-body">
            <div class="layui-form" lay-filter="searchForm">
                <div class="layui-row">
                    <div class="layui-col-md6">
                        <div class="layui-input-inline" style="width: 300px;">
                            <input type="text" id="searchKeyword" name="keyword" placeholder="搜索知识标题" class="layui-input">
                        </div>
                        <button class="za-btn za-btn-primary" id="btnSearch">
                            <i class="layui-icon layui-icon-search" style="margin-right: 5px;"></i>搜索
                        </button>
                        <button class="za-btn za-btn-secondary" id="btnReset" style="margin-left: 10px;">
                            重置
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 知识条目列表 -->
    <div class="layui-card">
        <div class="layui-card-body">
            <table class="layui-hide" id="knowledgeTable" lay-filter="knowledgeTable"></table>
        </div>
    </div>
    
    <!-- 添加/编辑知识条目弹窗 -->
    <div id="knowledgeFormDialog" style="display: none;">
        <form class="layui-form" id="knowledgeForm" lay-filter="knowledgeForm">
            <input type="hidden" id="knowledgeId" name="id">
            <div class="layui-form-item">
                <label class="layui-form-label" style="width: 80px;">标题 <span style="color: #ff4d4f;">*</span></label>
                <div class="layui-input-block">
                    <input type="text" id="knowledgeTitle" name="title" required lay-verify="required|maxlength" placeholder="请输入知识标题" maxlength="100"
                        autocomplete="off" class="layui-input">
                    <div class="layui-form-mid layui-word-aux">0/100</div>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label" style="width: 80px; vertical-align: top;">内容 <span style="color: #ff4d4f;">*</span></label>
                <div class="layui-input-block">
                    <textarea id="knowledgeContent" name="content" required lay-verify="required" placeholder="请输入知识内容" 
                        class="layui-textarea" style="height: 300px;"></textarea>
                    <div class="layui-form-mid layui-word-aux">支持基本文本格式</div>
                </div>
            </div>
        </form>
    </div>

    <script src="layui/layui.js"></script>
    <script>
        layui.use(['jquery', 'form', 'table', 'layer'], function() {
            var $ = layui.jquery;
            var form = layui.form;
            var table = layui.table;
            var layer = layui.layer;
            
            // 获取URL参数
            function getUrlParam(name) {
                var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
                var r = window.location.search.substr(1).match(reg);
                if (r != null) return unescape(r[2]);
                return null;
            }
            
            // 模拟数据
            var mockKnowledgeData = [
                { id: 1, title: '产品功能介绍', content: '我们的AI智能体平台提供智能对话、知识库管理、多模型支持等核心功能...', createTime: '2024-01-15 10:30:00' },
                { id: 2, title: '如何创建智能体', content: '1. 点击"创建智能体"按钮\n2. 填写智能体名称和系统提示词\n3. 设置可见性\n4. 点击保存', createTime: '2024-01-16 14:20:00' },
                { id: 3, title: '常见问题解答', content: 'Q: 智能体能记住对话历史吗？\nA: 是的，智能体支持多轮对话...', createTime: '2024-01-17 09:15:00' },
                { id: 4, title: 'API调用说明', content: '我们提供RESTful API接口，支持智能体的创建、编辑、删除等操作...', createTime: '2024-01-18 16:45:00' },
                { id: 5, title: '系统维护公告', content: '系统将于每周日凌晨2:00-4:00进行例行维护，请提前做好准备...', createTime: '2024-01-19 11:00:00' }
            ];
            
            // 渲染表格
            var knowledgeTable = table.render({
                elem: '#knowledgeTable',
                data: mockKnowledgeData,
                page: true,
                limit: 10,
                limits: [10, 20, 50],
                loading: true,
                cols: [[
                    { type: 'checkbox', fixed: 'left' },
                    { field: 'id', title: 'ID', width: 80, sort: true, fixed: 'left' },
                    { field: 'title', title: '标题', minWidth: 300, templet: function(d) {
                        return '<div style="font-weight: 500;">' + d.title + '</div>';
                    }},
                    { field: 'content', title: '内容预览', minWidth: 400, templet: function(d) {
                        var preview = d.content.replace(/\n/g, ' ').substring(0, 100);
                        return preview.length >= 100 ? preview + '...' : preview;
                    }},
                    { field: 'createTime', title: '创建时间', width: 180, sort: true },
                    { field: 'action', title: '操作', width: 150, fixed: 'right', templet: function() {
                        return '<button class="za-btn za-btn-sm za-btn-secondary btn-edit" style="margin-right: 5px;">编辑</button>' +
                               '<button class="za-btn za-btn-sm za-btn-danger btn-delete">删除</button>';
                    }}
                ]],
                done: function() {
                    // 编辑按钮点击事件
                    $('.btn-edit').on('click', function() {
                        var tr = $(this).closest('tr');
                        var data = table.cache['knowledgeTable'][tr.data('index')];
                        openKnowledgeForm(data);
                    });
                    
                    // 删除按钮点击事件
                    $('.btn-delete').on('click', function() {
                        var tr = $(this).closest('tr');
                        var data = table.cache['knowledgeTable'][tr.data('index')];
                        deleteKnowledge(data.id);
                    });
                }
            });
            
            // 表格复选框监听
            table.on('checkbox(knowledgeTable)', function(obj) {
                var checkStatus = table.checkStatus('knowledgeTable');
                if (checkStatus.data.length > 0) {
                    $('#btnBatchDelete').show();
                } else {
                    $('#btnBatchDelete').hide();
                }
            });
            
            // 搜索按钮点击事件
            $('#btnSearch').on('click', function() {
                var keyword = $('#searchKeyword').val().trim();
                var filteredData = mockKnowledgeData.filter(function(item) {
                    return item.title.indexOf(keyword) !== -1 || item.content.indexOf(keyword) !== -1;
                });
                
                table.reload('knowledgeTable', {
                    data: filteredData
                });
            });
            
            // 重置按钮点击事件
            $('#btnReset').on('click', function() {
                $('#searchKeyword').val('');
                table.reload('knowledgeTable', {
                    data: mockKnowledgeData
                });
            });
            
            // 添加知识按钮点击事件
            $('#btnAddKnowledge').on('click', function() {
                openKnowledgeForm();
            });
            
            // 批量删除按钮点击事件
            $('#btnBatchDelete').on('click', function() {
                var checkStatus = table.checkStatus('knowledgeTable');
                if (checkStatus.data.length === 0) {
                    layer.msg('请选择要删除的知识条目', { icon: 2 });
                    return;
                }
                
                var ids = checkStatus.data.map(function(item) { return item.id; });
                
                layer.confirm('确定要删除选中的 ' + ids.length + ' 条知识吗？', {
                    title: '确认删除',
                    icon: 3
                }, function(index) {
                    // 模拟删除操作
                    mockKnowledgeData = mockKnowledgeData.filter(function(item) {
                        return ids.indexOf(item.id) === -1;
                    });
                    
                    table.reload('knowledgeTable', {
                        data: mockKnowledgeData
                    });
                    
                    $('#btnBatchDelete').hide();
                    layer.msg('删除成功', { icon: 1 });
                    layer.close(index);
                });
            });
            
            // 打开知识表单弹窗
            function openKnowledgeForm(data) {
                // 清空表单
                $('#knowledgeForm')[0].reset();
                $('#knowledgeId').val('');
                
                // 如果是编辑模式，填充数据
                if (data) {
                    $('#knowledgeId').val(data.id);
                    $('#knowledgeTitle').val(data.title);
                    $('#knowledgeContent').val(data.content);
                }
                
                // 渲染表单
                form.render();
                
                // 打开弹窗
                var dialogTitle = data ? '编辑知识' : '添加知识';
                layer.open({
                    type: 1,
                    title: dialogTitle,
                    content: $('#knowledgeFormDialog'),
                    area: ['800px', '600px'],
                    btn: ['保存', '取消'],
                    yes: function(index) {
                        // 验证表单
                        form.verify();
                        form.on('submit(knowledgeForm)', function() {});
                        
                        // 获取表单数据
                        var formData = {
                            id: $('#knowledgeId').val(),
                            title: $('#knowledgeTitle').val(),
                            content: $('#knowledgeContent').val()
                        };
                        
                        // 模拟保存操作
                        if (formData.id) {
                            // 编辑
                            for (var i = 0; i < mockKnowledgeData.length; i++) {
                                if (mockKnowledgeData[i].id == formData.id) {
                                    mockKnowledgeData[i].title = formData.title;
                                    mockKnowledgeData[i].content = formData.content;
                                    break;
                                }
                            }
                            layer.msg('更新成功', { icon: 1 });
                        } else {
                            // 添加
                            var newId = Math.max.apply(Math, mockKnowledgeData.map(function(item) { return item.id; })) + 1;
                            mockKnowledgeData.push({
                                id: newId,
                                title: formData.title,
                                content: formData.content,
                                createTime: new Date().toLocaleString('zh-CN', {
                                    year: 'numeric',
                                    month: '2-digit',
                                    day: '2-digit',
                                    hour: '2-digit',
                                    minute: '2-digit',
                                    second: '2-digit',
                                    hour12: false
                                }).replace(/\//g, '-')
                            });
                            layer.msg('添加成功', { icon: 1 });
                        }
                        
                        // 刷新表格
                        table.reload('knowledgeTable', {
                            data: mockKnowledgeData
                        });
                        
                        layer.close(index);
                    }
                });
            }
            
            // 删除知识
            function deleteKnowledge(id) {
                layer.confirm('确定要删除这条知识吗？', {
                    title: '确认删除',
                    icon: 3
                }, function(index) {
                    // 模拟删除操作
                    mockKnowledgeData = mockKnowledgeData.filter(function(item) {
                        return item.id !== id;
                    });
                    
                    table.reload('knowledgeTable', {
                        data: mockKnowledgeData
                    });
                    
                    layer.msg('删除成功', { icon: 1 });
                    layer.close(index);
                });
            }
            
            // 检查URL参数中的智能体ID
            var agentId = getUrlParam('agentId');
            if (agentId) {
                // 在实际应用中，这里应该根据agentId从服务器获取智能体信息
                $('#agentInfo').text('智能体 ' + agentId + ' 的知识库');
                
                // 模拟根据agentId筛选知识库数据
                console.log('加载智能体ID为 ' + agentId + ' 的知识库');
            }
        });
    </script>
</body>
</html>